import { WebSocket } from "ws";
import { User } from "../../../types/User";
import { roomsTable } from "../../../database/rooms-table";
import { conversionMessage } from "../helpers/message-converter";
import { GetPlayerCardsMessageData } from "../types/MessageData";
import { Card } from "../../../types/Card";

export const getPlayerCardsHandler = ({ user, payload }: { client: WebSocket; user: User; payload: GetPlayerCardsMessageData["payload"] }) => {
	const room = roomsTable.rooms.find((v) => v.roomId == payload.roomId);
	const player = room?.players.find((v) => v.user.userId == user.userId);
	const targetPlayer = room?.players.find((v) => v.user.userId == payload.userId);
	if (room && player && targetPlayer) {
		const selectedCards: Card[] = [];
		payload.cardIds.forEach((cardId) => {
			const handCardsIndex = targetPlayer.handCards.findIndex((v) => v.cardId === cardId);
			if (handCardsIndex !== -1) {
				selectedCards.push(targetPlayer.handCards[handCardsIndex]);
				targetPlayer.handCards.splice(handCardsIndex, 1);
				return;
			}
			const materielCardsIndex = targetPlayer.materielCards.findIndex((v) => v.cardId === cardId);
			if (materielCardsIndex !== -1) {
				selectedCards.push(targetPlayer.materielCards[materielCardsIndex]);
				targetPlayer.materielCards.splice(materielCardsIndex, 1);
				return;
			}
			const delayedCardsIndex = targetPlayer.delayedCards.findIndex((v) => v.cardId === cardId);
			if (delayedCardsIndex !== -1) {
				selectedCards.push(targetPlayer.delayedCards[delayedCardsIndex]);
				targetPlayer.delayedCards.splice(delayedCardsIndex, 1);
				return;
			}
			const buckleCardsIndex = targetPlayer.buckleCards.findIndex((v) => v.cardId === cardId);
			if (buckleCardsIndex !== -1) {
				selectedCards.push(targetPlayer.buckleCards[buckleCardsIndex]);
				targetPlayer.buckleCards.splice(buckleCardsIndex, 1);
				return;
			}
		});
		player.handCards.push(...selectedCards);
		room.players.forEach((v) => v.client!.send(conversionMessage({ type: "gotPlayerCards", payload: { roomId: room.roomId, userId: user.userId, cards: selectedCards } })));
		const log = { userId: user.userId, username: user.username, log: "获取了" + targetPlayer.user.username + "的" + selectedCards.length + "张牌。" };
		room.logs.push(log);
		room.players.forEach((v) => v.client!.send(conversionMessage({ type: "roomLog", payload: log })));
	}
};
